from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response

from goods.models import SKUImage, SKU
from celery_tasks.static_file.tasks import get_detail_html


class ImagesSerializer(serializers.ModelSerializer):
    """
    图片序列化器
    """
    # sku = serializers.PrimaryKeyRelatedField()

    class Meta:
        model = SKUImage
        fields = '__all__'

    def create(self, validated_data):
        # 3 建立fastdfs客户端
        client = Fdfs_client(settings.FASTDFS_PATH)
        # file = request.FILES.get('image')
        # 获取request对象
        file = self.context['request'].FILES.get('image')

        # 4 上传图片
        # res = client.upload_by_buffer(file)  因为读取的是二进制数据，所以需要下面那种形式才能读到
        res = client.upload_by_buffer(file.read())

        # 5 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response({'error': '图片上传失败'})

        # 6 保存图片表
        img = SKUImage.objects.create(sku_id=validated_data['sku'].id, image=res['Remote file_id'])
        # # img = SKUImage.objects.create(sku=ser.validated_data['sku'], image=res['Remote file_id'])

        # 保存完图片还要重新生成详情页面，为了减少延时，选择异步任务(调用异步任务时，不能直接传对象)
        get_detail_html(img.sku.id)

        return img

    def update(self, instance, validated_data):
        # 3 建立fastdfs客户端
        client = Fdfs_client(settings.FASTDFS_PATH)
        # file = request.FILES.get('image')
        # 获取request对象
        file = self.context['request'].FILES.get('image')

        # 4 上传图片
        # res = client.upload_by_buffer(file)  因为读取的是二进制数据，所以需要下面那种形式才能读到
        res = client.upload_by_buffer(file.read())

        # 5 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response({'error': '图片上传失败'})

        # # 6 保存图片表
        # img = SKUImage.objects.create(sku_id=validated_data['sku'].id, image=res['Remote file_id'])
        # # img = SKUImage.objects.create(sku=ser.validated_data['sku'], image=res['Remote file_id'])

        # 6 更新图片
        instance.image = res['Remote file_id']
        instance.save()

        # 异步生成详情静态页面
        get_detail_html(instance.sku.id)

        return instance


class SKUserializer(serializers.ModelSerializer):
    """
    sku序列化器
    """
    class Meta:
        model = SKU
        fields = ('id', 'name')